package com.kjs.web.cacheService.impl;

import com.kjs.common.resultModel.JwtUser;
import com.kjs.web.dao.mapper.ICustomersMapper;
import com.kjs.web.pojo.Customers;
import com.kjs.web.cacheService.IJwtUserCacheService;
import com.kjs.web.Util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author xuedingjiexueergou@gmail.com
 * @date 2018/10/16 9:54
 */
@Service
@Slf4j
public class JwtUserCacheServiceImpl implements IJwtUserCacheService {

    @Autowired
    private ICustomersMapper customersMapper;

    @Override
    public JwtUser findJwtUserById(Integer id) {
        log.info("从中根据登录id:{} 获取登录记录", id);
        return (JwtUser)loadUserByUsername(id.toString());
    }

    @Override
    public JwtUser save(JwtUser user) {
        log.info("保存登录用户到缓存: {}", user.getId());
        return user;
    }

    @Override
    public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException {
        Customers customers = customersMapper.getById(Integer.parseInt(id));
        if (customers == null){
            throw new UsernameNotFoundException(id);
        }
        return JwtUtil.fromJwtUser(customers);
    }
}
